<!-- 添加用户组件 -->
<template>
    <div class='user-add'>
        <!-- 导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>添加用户</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card class="box-card">
            <el-row>
                <el-col :span="18">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <!-- prop="username":校验的属性 
                        ruleForm:放置提交后台的数据所有属性
                        -->
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="ruleForm.username"></el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="password">
                            <el-input placeholder="请输入密码" v-model="ruleForm.password" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="checkPass">
                            <el-input placeholder="请再次输入密码" v-model="ruleForm.checkPass" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="ruleForm.email"></el-input>
                        </el-form-item>
                        <el-form-item label="性别" prop="sex">
                            <el-radio-group v-model="ruleForm.sex">
                                <el-radio label="男">男</el-radio>
                                <el-radio label="女">女</el-radio>
                                <el-radio label="保密">保密</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="ruleForm.phone"></el-input>
                        </el-form-item>
                        <el-form-item label="等级" prop="level">
                            <el-radio-group v-model="ruleForm.level">
                                <el-radio label="1">管理员</el-radio>
                                <el-radio label="2">普通用户</el-radio>
                                <el-radio label="3">VIP用户</el-radio>
                                <el-radio label="4">游客</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="年龄" prop="age">
                            <!-- 修饰符 -->
                            <el-input v-model.number="ruleForm.age"></el-input>
                        </el-form-item>
                        <el-form-item label="地址" prop="address">
                            <el-input v-model="ruleForm.address"></el-input>
                        </el-form-item>
                        <!-- <el-form-item label="是否显示" prop="is_show">
                            <el-switch v-model="ruleForm.is_show" active-text="是" inactive-text="否" active-value="1">
                            </el-switch>
                        </el-form-item> -->
                        <el-form-item label="用户头像">
                            <el-upload class="avatar-uploader" :action="Setting.baseURLRe + '/api/upload/img'"
                                :show-file-list="true" :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="ruleForm.imgsrc" :src="Setting.baseURL + ruleForm.imgsrc" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="submitForm('ruleForm')">添加用户</el-button>
                            <el-button @click="resetForm('ruleForm')">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Setting from '@/utils/setting'
import validateReg from '@/utils/validateReg'
import { UserAddApi } from '@/api/user'
export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        //这里存放数据
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'));
            } else {
                if (this.ruleForm.checkPass !== '') {
                    this.$refs.ruleForm.validateField('checkPass');
                }
                callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.ruleForm.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        var validatePhone = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入手机号'));
            } else {
                if (!validateReg.regPhone.test(value)) {
                    callback(new Error('请输入正确的手机号'));
                }
                callback();
            }
        };
        var validateEmail = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入邮箱'));
            } else {
                if (!validateReg.regEmail.test(value)) {
                    callback(new Error('请输入正确的邮箱'));
                }
                callback();
            }
        };
        return {
            Setting,
            ruleForm: {
                username: '',
                password: '',
                sex: '保密',
                phone: '',
                level: '2',
                age: '',
                email: '',
                address: '',
                is_show: '1',
                imgsrc: ''
            },
            rules: {
                // required:必须填入
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 18, message: '长度在 2 到 18 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, validator: validatePass, trigger: 'blur' }
                ],
                checkPass: [
                    { required: true, validator: validatePass2, trigger: 'blur' }
                ],
                age: [
                    { type: 'number', message: '年龄必须为数字值', trigger: 'blur' }
                ],
                phone: [
                    { required: true, validator: validatePhone, trigger: 'blur' }
                ],
                email: [
                    { required: true, validator: validateEmail, trigger: 'blur' }
                ],
            }
        };
    },
    //计算属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
        handleAvatarSuccess(res, file) {
            console.log(file);
            console.log(res);
            // console.log(URL.createObjectURL(file.raw));
            this.ruleForm.imgsrc = res.data.name
        },
        // 校验图片格式的操作
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 添加提交
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    UserAddApi(this.ruleForm).then(res => {
                        if (res.data.status == 200) {
                            // 跳转到列表页面
                            this.$router.push('/admin/userlist');
                        } else {
                            this.$message(res.data.msg);
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 重置
        resetForm(formName) {
            this.$refs[formName].resetFields();
        }


    },
    beforeCreate() { }, //生命周期 - 创建之前
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    beforeMount() { }, //生命周期 - 挂载之前
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {

    },
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，激活
    deactivated() { }, //如果页面有keep-alive缓存功能，非激活
}
</script>
<style>

</style>